const fs = require("fs");
const async = require("async");
const path = require("path");
const Result = require("../utils/result");
const BaseController = require("./base/base");
class UploadController extends BaseController {
  constructor() {
    super();
    this.uploadDir = "/upload";
    this.tasks = [];
    this.paths = [];
    this.srcs = [];
    this.urls = [];
  }
  upload(req, res, next) {
    req.files.forEach((file) => {
      this.tasks.push((callback) => {
        const originalname = file.originalname;
        const filename = file.filename;
        let suffix = originalname.substr(filename.length);
        if(suffix == "") {
         let index = originalname.lastIndexOf(".");
         suffix = originalname.substr(index);
        }
        const newFileName = this.getRandomName(1000, 9999, suffix);
        const destPath = path.join(
          __dirname,
          "../public",
          this.uploadDir,
          newFileName
        );
        this.copyFile(file.path, destPath, callback);
        this.paths.push(destPath);
        this.srcs.push(path.join(this.uploadDir, newFileName));
        this.urls.push(
          "http://" +  path.join(req.headers.host, this.uploadDir, newFileName)
        );
      });
    });
    async.parallel(this.tasks, (err, ret) => {
      if (err) return res.json(Result.fail(err.message));
      let response = Result.ok("success",{ path: this.paths, src: this.srcs, url: this.urls });
      this.tasks = [];
      this.paths = [];
      this.srcs = [];
      this.urls = [];
      res.json(response);
    });
  }
  copyFile(srcPath, destPath, callback) {
    fs.readFile(srcPath, (err, data) => {
      if (err) return callback && callback(err, null);
      fs.writeFile(destPath, data, (err) => {
        callback && callback(null, "ok");
      });
    });
  }
  getRandomName(min, max, suffix) {
    return (
      new Date().getTime() +
      "" +
      (Math.round(Math.random() * (max - min)) + min) + "." +
      suffix
    );
  }
}
module.exports = new UploadController().resolve();